#include <QMouseEvent>

#include "treewidget.h"
#include "formmain.h"


TreeWidget::TreeWidget(QWidget *parent) : QTreeWidget(parent) {
    setHeader(new EditableTreeHeader(this));
}

void TreeWidget::mousePressEvent(QMouseEvent *event) {
    QTreeWidget::mousePressEvent(event);
    emit mousePressed(event);
}

void TreeWidget::keyPressEvent(QKeyEvent *event) {
	QTreeWidget::keyPressEvent(event);
    emit keyPressed(event);
}

QString TreeWidget::currentTopLevelText(int column) {
	QString ret;
	QTreeWidgetItem *current = currentItem();

	if (current) {
		while (current->parent()) {
			current = current->parent();
		}
		ret = current->text(column);
	}

	return ret;
}

EditableTreeHeader::EditableTreeHeader(TreeWidget *parent)
    : QHeaderView(Qt::Horizontal, parent),
      m_menu(0),
      m_parent(parent) {
    setContextMenuPolicy(Qt::CustomContextMenu);

    connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(customContextMenu(const QPoint&)));
}

void EditableTreeHeader::customContextMenu(const QPoint &point) {
	// Prepare actions for columns.
    if (!m_menu) {
        m_menu = new QMenu(this);
        QAction *title = new QAction(tr("Configure Headers"), this);
        title->setEnabled(false);
        m_menu->addAction(title);

        QTreeWidgetItem *item = m_parent->headerItem();

		// The 1st column has be always there and enabled. So start from 1.
        for (int i = 1; i < item->columnCount(); ++i) {
            QAction *a = new QAction(item->text(i), this);
            a->setCheckable(true);
            a->setChecked(!m_parent->isColumnHidden(i));
            a->setData(i);
            connect(a, SIGNAL(triggered()), this, SLOT(columnActionHandler()));
            m_menu->addAction(a);
        }
    }

    m_menu->exec(mapToGlobal(point));
}

void EditableTreeHeader::columnActionHandler() {
    QAction *a = qobject_cast<QAction*>(sender());
    Q_ASSERT(a);
    m_parent->setColumnHidden(a->data().toInt(), !a->isChecked());
}
